package com.bsj.sipgateway.mysql.bsj.vehicle.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.bsj.sipgateway.cache.ResetChannelCache;
import com.bsj.sipgateway.cache.VehicleCache;
import com.bsj.sipgateway.common.def.CameraDto;
import com.bsj.sipgateway.mysql.bsj.vehicle.entity.Vehicle;
import com.bsj.sipgateway.mysql.bsj.vehicle.mapper.VehicleMapper;
import com.bsj.sipgateway.mysql.bsj.vehicle.service.IVehicleService;
import com.bsj.sipgateway.sip.bean.VehicleInfo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * <p>
 * 车辆信息 服务实现类
 * </p>
 *
 * @author wph
 * @since 2022-08-04
 */
@Service
@Slf4j
public class VehicleServiceImpl extends ServiceImpl<VehicleMapper, Vehicle> implements IVehicleService {

    @Autowired(required = false)
    private VehicleMapper vehicleMapper;

//    @Autowired
//    private CommandUpProducer commandUpProducer;

    private static ReentrantReadWriteLock rwlock = new ReentrantReadWriteLock();

    public List<Vehicle> queryVehicleAndGroup() {
        return vehicleMapper.queryVehicleAndGroup();
    }

    public int updateChannelId(String deviceId, String channelId) {
        if (StringUtils.isNotBlank(deviceId) && StringUtils.isNotBlank(channelId)) {
            return vehicleMapper.updateChannelId(deviceId, channelId);
        } else {
            return 0;
        }
    }

    //根据已经设置好的别名和通道号设置通道id    逆天需求把key-value关系用str数组存起来             //这个需求又被弃用掉了，改成更复杂的三个字段对应
    public int updateChannelByAliasName(String device, String aliasName, String channelId) {
        QueryWrapper<Vehicle> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("vehicleId", "groupId", "terminalNo", "plate", "cameraLine", "cameraAlias", "cameraChannelId");
        queryWrapper.eq("terminalNo", device);
        synchronized (this) {
            Vehicle vehicle = vehicleMapper.selectOne(queryWrapper);
            String[] cameraAlias = null;
            List<String> cameraAliasMap = new ArrayList<>();
            if (vehicle != null) {
                if (StringUtils.isNotEmpty(vehicle.getCameraAlias())) {
                    cameraAlias = vehicle.getCameraAlias().replace("[", "").replace("]", "").split(",");
                    cameraAliasMap.addAll(Arrays.asList(cameraAlias));
                }
                int index = -1;
                for (int i = 0; i < cameraAliasMap.size(); i++) {
                    if (aliasName.equals(cameraAliasMap.get(i))) {
                        index = i;
                    }
                }
                if (index != -1) {
                    String idxNum = "1";
                    String[] cameraLine = null;
                    List<String> cameraLineList = new ArrayList<>();
                    if (StringUtils.isNotEmpty(vehicle.getCameraLine())) {
                        cameraLine = vehicle.getCameraLine().replace("[", "").replace("]", "").split(",");
                        cameraLineList.addAll(Arrays.asList(cameraLine));
                    }
                    idxNum = cameraLineList.get(index);

                    //更新缓存
                    VehicleInfo vehicleInfo = VehicleCache.get(device);
                    vehicleInfo.getChannelMap().put(idxNum, channelId);

                    String cameraChannelId = vehicle.getCameraChannelId();
                    if (StringUtils.isNotBlank(cameraChannelId) && cameraChannelId.contains("[") && cameraChannelId.contains("]")) {
                        //已有，修改值，注意下标
                        String channelList = cameraChannelId.substring(1, cameraChannelId.length() - 1);
                        String[] split = channelList.split(",");
                        if (split.length <= index) {
                            String[] newChannel = new String[index + 1];
                            for (int i = 0; i < split.length; i++) {
                                newChannel[i] = split[i];
                            }
                            newChannel[index] = channelId;
                            String updateChannel = Arrays.toString(newChannel);
                            return updateChannelId(device, updateChannel);
                        } else {
                            split[index] = channelId;
                            String updateChannel = Arrays.toString(split).replaceAll(" ", "");
                            return updateChannelId(device, updateChannel);
                        }
                    } else {//没有，第一次赋值
                        String updateChannel = "[";
                        for (int i = 0; i < index; i++) {
                            updateChannel += ",";
                        }
                        updateChannel += channelId;
                        updateChannel += "]";
                        return updateChannelId(device, updateChannel);
                    }
                } else {
                    log.info("设备：{}没有对应的别名：{}", device, aliasName);
                    return 0;
                }
            }
        }
        log.info("数据库没有对应设备：{}", device);
        return 0;
    }

    public int upDateChannel(String device, String aliasName, String channelId) {
        rwlock.writeLock().lock();
        try {
            Integer flag = ResetChannelCache.getResetFlag(device);


            int index = Integer.parseInt(channelId.substring(channelId.length() - 2));
            //这里加锁是因为设备上传列表时，可能分多次同时上传，有可能造成后面读写把前面覆盖的情况
            VehicleInfo vehicleInfo = VehicleCache.get(device);

            if (flag == 1) {
                log.info("设备：" + device + "重设通道号，设备类型：" + vehicleInfo.getTerminalType() + ",channelId:" + channelId + ",aliasName:" + aliasName);
                if ("GB28181".equals(vehicleInfo.getTerminalType())) {
                    index = 1;
                }
                vehicleInfo.getChannelMap().put("" + index, channelId);

                String line = "[" + index + "]";
                aliasName = "[" + aliasName + "]";
                channelId = "[" + channelId + "]";

                log.info("重设通道号：" + device + ",:" + aliasName);
                int i = vehicleMapper.resetChannel(device, line, aliasName, channelId);
                QueryWrapper<Vehicle> queryWrapper = new QueryWrapper<>();
                queryWrapper.select("vehicleId", "groupId", "terminalNo", "plate", "cameraLine", "cameraAlias", "cameraChannelId");
                queryWrapper.eq("terminalNo", device);
                Vehicle vehicle = vehicleMapper.selectOne(queryWrapper);

                sendMqUpdate(vehicle);
                return i;
            } else {


                QueryWrapper<Vehicle> queryWrapper = new QueryWrapper<>();
                queryWrapper.select("vehicleId", "groupId", "terminalNo", "plate", "cameraLine", "cameraAlias", "cameraChannelId");
                queryWrapper.eq("terminalNo", device);
                Vehicle vehicle = vehicleMapper.selectOne(queryWrapper);
                if (vehicle != null) {
                    //获取当前的list有多少位，往后面加一位

                    //1、通道号
                    String[] cameraLine = null;
                    List<String> cameraLineList = new ArrayList<>();
                    if (StringUtils.isNotEmpty(vehicle.getCameraLine())) {
                        cameraLine = vehicle.getCameraLine().replace("[", "").replace("]", "").split(",");
                        cameraLineList.addAll(Arrays.asList(cameraLine));
                    }

                    if ("GB28181".equals(vehicleInfo.getTerminalType())) {
                        if (null != cameraLine) {
                            index = cameraLine.length + 1;
                        }
                    }
                    log.info("设备：" + device + "更新通道号，设备类型：" + vehicleInfo.getTerminalType() + ",channelId:" + channelId + ",aliasName:" + aliasName + ",cameraLine:" + vehicle.getCameraLine() + ",index:" + index);

                    cameraLineList.add("" + index);

                    //2、别名
                    String[] cameraAlias = null;
                    List<String> cameraAliasList = new ArrayList<>();
                    if (StringUtils.isNotEmpty(vehicle.getCameraAlias())) {
                        cameraAlias = vehicle.getCameraAlias().replace("[", "").replace("]", "").split(",");
                        cameraAliasList.addAll(Arrays.asList(cameraAlias));
                        cameraAliasList.add(aliasName);
                    }

                    //3、通道id
                    String[] cameraChannelId = null;
                    List<String> cameraChannelList = new ArrayList<>();
                    if (StringUtils.isNotEmpty(vehicle.getCameraChannelId())) {
                        cameraChannelId = vehicle.getCameraChannelId().replace("[", "").replace("]", "").split(",");
                        //判断是否已有通道id，如果已有直接跳过
                        for (String oldChannelId : cameraChannelId) {
                            if (channelId.equals(oldChannelId)) {
                                log.info("设备：{}，通道id：{}已存在，不做操作。", device, channelId);
                                return 0;
                            }
                        }

                        cameraChannelList.addAll(Arrays.asList(cameraChannelId));
                        cameraChannelList.add(channelId);
                    }
                    vehicleInfo.getChannelMap().put("" + index, channelId);
                    log.info("更新通道号：" + device + "," + Arrays.toString(cameraAliasList.toArray()));

                    int i = vehicleMapper.resetChannel(device,
                            Arrays.toString(cameraLineList.toArray()).replaceAll(" ", ""),
                            Arrays.toString(cameraAliasList.toArray()).replaceAll(" ", ""),
                            Arrays.toString(cameraChannelList.toArray()).replaceAll(" ", ""));

                    Vehicle vehicleMQ = new Vehicle();
                    vehicleMQ.setVehicleId(vehicle.getVehicleId());
                    vehicleMQ.setTerminalNo(vehicle.getTerminalNo());
                    vehicleMQ.setCameraLine(Arrays.toString(cameraLineList.toArray()).replaceAll(" ", ""));
                    vehicleMQ.setCameraAlias(Arrays.toString(cameraAliasList.toArray()).replaceAll(" ", ""));
                    vehicleMQ.setCameraChannelId(Arrays.toString(cameraChannelList.toArray()).replaceAll(" ", ""));
                    sendMqUpdate(vehicleMQ);

                    return i;
                } else {
                    log.warn("更新通道号时找不到设备：" + device);
                }

            }
        } finally {
            rwlock.writeLock().unlock();
        }
        return 0;
    }


    public int updateExpireDate(String deviceId) {
        return vehicleMapper.updateExpireDate(deviceId);
    }

    public int sendMqUpdate(Vehicle vehicle) {
        if (vehicle != null) {
            CameraDto cameraDto = new CameraDto(vehicle.getVehicleId(), vehicle.getTerminalNo(), vehicle.getCameraLine(), vehicle.getCameraAlias(), vehicle.getCameraChannelId());

//            commandUpProducer.send(cameraDto);
        }
        return 1;
    }


}
